<template>
  <Card>
    <div id="addInsure">
      <div class="title">
        <Icon size="18" type="md-list-box"/>
        编辑车辆信息
        <Divider/>
      </div>
      <div class="from">
        <Form ref="editForm" :label-width="170" :model="editForm" :rules="editFormValidate" inline>
          <div class="fromTitle">基础信息</div>
          <Row>
            <Col span="10">
            <Form-item label="车牌号：" prop="license_plate_num">
              <Select v-model="editForm.license_plate_num" clearable @on-change="changeBus">
                <Option
                  v-for="item in busListData"
                  :key="item.id"
                  :value="item.id"
                >{{ item.license_plate_num }}
                </Option>
              </Select>
            </Form-item>
            </Col>
            <Col span="10">
            <FormItem label="车辆类型：">
              <Input v-model="editForm.type" placeholder readonly/>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="10">
            <FormItem label="发动机号：">
              <Input v-model="editForm.engine_num" placeholder readonly/>
            </FormItem>
            </Col>
            <Col span="10">
            <FormItem label="车架号：">
              <Input v-model="editForm.frame_nun" placeholder readonly/>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="10">
            <FormItem label="核载人数：">
              <Input v-model="editForm.max_num" placeholder readonly/>
            </FormItem>
            </Col>
          </Row>
          <div class="fromTitle">交强险信息</div>
          <Row>
            <Col span="10">
            <FormItem label="金额：">
              <Input v-model="editForm.force_money" placeholder/>
            </FormItem>
            </Col>
            <Col span="10">
            <FormItem label="保单时间：">
              <DatePicker
                v-model="editForm.force_time"
                format="yyyy-MM-dd"
                placeholder="选择时间"
                type="date"
                @on-change="editForm.force_time=$event"
              ></DatePicker>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="10">
            <FormItem label="保险开始时间：">
              <DatePicker
                v-model="editForm.force_start_date"
                format="yyyy-MM-dd"
                placeholder="选择时间"
                type="date"
                @on-change="editForm.force_start_date=$event"
              ></DatePicker>
            </FormItem>
            </Col>
            <Col span="10">
            <FormItem label="保险结束时间：">
              <DatePicker
                v-model="editForm.force_end_date"
                format="yyyy-MM-dd"
                placeholder="选择时间"
                type="date"
                @on-change="editForm.force_end_date=$event"
              ></DatePicker>
            </FormItem>
            </Col>
          </Row>
          <div class="fromTitle">商业险信息</div>
          <Row>
            <Col span="10">
            <FormItem label="金额：">
              <Input v-model="editForm.merc_money" placeholder/>
            </FormItem>
            </Col>
            <Col span="10">
            <FormItem label="保单时间：">
              <DatePicker
                v-model="editForm.merc_time"
                format="yyyy-MM-dd"
                placeholder="选择时间"
                type="date"
                @on-change="editForm.merc_time=$event"
              ></DatePicker>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="10">
            <FormItem label="保险开始时间：">
              <DatePicker
                v-model="editForm.merc_start_date"
                format="yyyy-MM-dd"
                placeholder="选择时间"
                type="date"
                @on-change="editForm.merc_start_date=$event"
              ></DatePicker>
            </FormItem>
            </Col>
            <Col span="10">
            <FormItem label="保险结束时间：">
              <DatePicker
                v-model="editForm.merc_end_date"
                format="yyyy-MM-dd"
                placeholder="选择时间"
                type="date"
                @on-change="editForm.merc_end_date=$event"
              ></DatePicker>
            </FormItem>
            </Col>
            <Col span="10">
            <FormItem label="承保公司：">
              <Input v-model="editForm.merc_company" placeholder="请输入保险公司"/>
            </FormItem>
            </Col>
          </Row>
          <div class="fromTitle">承运人责任险信息</div>
          <Row>
            <Col span="10">
            <FormItem label="金额：">
              <Input v-model="editForm.liability_money" placeholder/>
            </FormItem>
            </Col>
            <Col span="10">
            <FormItem label="保单时间：">
              <DatePicker
                v-model="editForm.liability_time"
                format="yyyy-MM-dd"
                placeholder="选择时间"
                type="date"
                @on-change="editForm.liability_time=$event"
              ></DatePicker>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="10">
            <FormItem label="保险开始时间：">
              <DatePicker
                v-model="editForm.liability_start_date"
                format="yyyy-MM-dd"
                placeholder="选择时间"
                type="date"
                @on-change="editForm.liability_start_date=$event"
              ></DatePicker>
            </FormItem>
            </Col>
            <Col span="10">
            <FormItem label="保险结束时间：">
              <DatePicker
                v-model="editForm.liability_end_date"
                format="yyyy-MM-dd"
                placeholder="选择时间"
                type="date"
                @on-change="editForm.liability_end_date=$event"
              ></DatePicker>
            </FormItem>
            </Col>
          </Row>
          <div class="fromTitle">保险文件上传</div>
          <div class="btns">
            <upload-file
              ref="uploadFile"
              :params="{saveDir: 'insure', type: 'file'}"
              button-name="上传附件"
              @on-change="refreshTable($event)"
            ></upload-file>
          </div>
          <div style="margin-bottom:15px">
            <Table
              ref="selection"
              :columns="columns"
              :data="editForm.files"
              border
              height="350"
              size="small"
              stripe
            ></Table>
          </div>
          <div style="height:50px;"></div>
          <div class="fromItem">
            <FormItem label>
              <Button
                :loading="submitLoading"
                icon="md-checkmark-circle"
                style="margin-right:10px"
                type="primary"
                @click="handleSubmit()"
              >保存修改
              </Button>
            </FormItem>
          </div>
        </Form>
      </div>
    </div>
  </Card>
</template>
<script>
import './insure.css'
import {editInsure, insureInfo} from '../../api/insure'
import {busList} from '../../api/bus'
import UploadFile from '../my-components/upload-file'
import Viewer from 'viewerjs'

export default {
  components: {
    UploadFile
  },
  data() {
    return {
      submitLoading: false,
      submitResetLoading: false,
      editForm: {
        merc_money: 0,
        files: []
      },
      editFormValidate: {},
      busListData: [],
      dict: [],
      columns: [
        {
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: '附件名称',
          key: 'file_name',
          align: 'left'
        },
        {
          title: '缩略图（点击预览）',
          key: 'file_path',
          width: 150,
          align: 'center',
          render: (h, params) => {
            if (this.isInArray(['jpg', 'png', 'jpeg'], params.row.file_type)) {
              return h('img', {
                attrs: {
                  src: params.row.file_path
                },
                style: {
                  cursor: 'zoom-in',
                  width: '80px',
                  height: '60px',
                  margin: '10px 0',
                  'object-fit': 'contain'
                },
                on: {
                  click: () => {
                    this.showPic(params.row)
                  }
                }
              })
            } else if (this.isInArray(['doc', 'docx'], params.row.file_type)) {
              return h('img', {
                attrs: {
                  src: require('../../images/icon/word.png')
                },
                style: {
                  width: '55px',
                  height: '60px',
                  margin: '10px 0',
                  'object-fit': 'contain'
                },
                on: {
                  click: () => {
                    this.$Message.warning('暂不支持预览')
                  }
                }
              })
            } else if (this.isInArray(['xls', 'xlsx'], params.row.file_type)) {
              return h('img', {
                attrs: {
                  src: require('../../images/icon/excel.png')
                },
                style: {
                  width: '80px',
                  height: '60px',
                  margin: '10px 0',
                  'object-fit': 'contain'
                },
                on: {
                  click: () => {
                    this.$Message.warning('暂不支持预览')
                  }
                }
              })
            } else if (params.row.file_type === 'pdf') {
              return h('img', {
                attrs: {
                  src: require('../../images/icon/pdf.png')
                },
                style: {
                  cursor: 'zoom-in',
                  width: '60px',
                  margin: '10px 0',
                  'object-fit': 'contain'
                },
                on: {
                  click: () => {
                    this.$Message.warning('暂不支持预览')
                  }
                }
              })
            } else {
              return h('img', {
                attrs: {
                  src: require('../../images/icon/file.png')
                },
                style: {
                  width: '55px',
                  height: '60px',
                  margin: '10px 0',
                  'object-fit': 'contain'
                },
                on: {
                  click: () => {
                    this.$Message.warning('暂不支持预览')
                  }
                }
              })
            }
          }
        },
        {
          title: '附件格式',
          key: 'file_type',
          align: 'center'
        },
        {
          title: '文件大小',
          key: 'size',
          width: 115,
          sortable: true,
          render: (h, params) => {
            const file_size = params.row.file_size
            const m = file_size >= 51200 ?
              ((params.row.file_size * 1.0) / (1024 * 1024)).toFixed(2) + ' MB' :
              ((params.row.file_size * 1.0) / 1024).toFixed(2) + ' KB'
            return h('span', m)
          }
        },
        {
          title: '上传时间',
          key: 'created_at',
          align: 'center'
        },
        {
          title: '上传人员',
          key: 'user_name',
          align: 'center'
        },
      ]
    }
  },
  watch: {
    $route: function () {
      if (this.$route.params.id !== undefined) {
        this.getBusList()
      }
    }
  },
  mounted() {
    if (this.$route.params.id !== undefined) {
      this.getBusList()
    } else {
      this.$store.commit('closeTag', 'editInsure')
      this.$router.push({
        name: 'insure'
      })
    }
  },
  methods: {
    showPic(v) {
      const image = new Image()
      image.src = v.file_path
      const viewer = new Viewer(image, {
        hidden: function () {
          viewer.destroy()
        }
      })
      viewer.show()
    },
    isInArray(arr, str) {
      const testStr = ',' + arr.join(',') + ','
      return testStr.indexOf(',' + str + ',') !== -1
    },
    changeBus(em) {
      const _this = this
      this.busListData.forEach(function (e) {
        if (em === e.id) {
          _this.editForm.type = e.type
          _this.editForm.engine_num = e.engine_num
          _this.editForm.frame_nun = e.frame_nun
          _this.editForm.max_num = e.max_num
        }
      })
    },
    refreshTable(event) {
      this.editForm.files.push(event.detail)
    },
    getBusList() {
      busList().then(res => {
        if (res.data) {
          this.busListData = res.data.personnel
          this.getInsureInfo()
        }
      })
    },
    getInsureInfo() {
      insureInfo({id: this.$route.params.id}).then(res => {
        if (res.data) {
          this.editForm = res.data.result
          this.editForm.license_plate_num = parseInt(
            res.data.result.license_plate_num
          )
          this.editForm.id = res.data.result.id
        }
      })
    },
    handleReset() {
      this.$refs.editForm.resetFields()
      this.editForm = {}
      this.editForm.files = []
    },
    handleSubmit() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          editInsure(this.editForm).then(res => {
            this.submitLoading = false
            if (res.data) {
              this.$Message.success(res.message)
              this.$store.commit('closeTag', 'editInsure')
              this.$router.push({
                name: 'insure'
              })
            } else {
              this.$Message.error(res.message)
            }
          })
        }
      })
    }
  }
}
</script>
<style>
.ivu-row .ivu-col .ivu-form-item {
  width: 100%;
}
</style>
